package com.easybbs.controller;

import com.easybbs.annotation.Globallnterceptor;
import com.easybbs.annotation.VerifyParam;
import com.easybbs.entity.constants.Constants;
import com.easybbs.entity.dto.SessionWebUserDto;
import com.easybbs.entity.enums.*;
import com.easybbs.entity.po.ForumComment;
import com.easybbs.entity.po.LikeRecord;
import com.easybbs.entity.query.ForumCommentQuery;
import com.easybbs.entity.vo.ResponseVO;
import com.easybbs.exception.BusinessException;
import com.easybbs.service.ForumCommentService;
import com.easybbs.service.LikeRecordService;
import com.easybbs.utils.StringTools;
import com.easybbs.utils.SysCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class ForumCommentController extends BaseController {
    @Autowired
    private ForumCommentService forumCommentService;

    @Autowired
    private LikeRecordService likeRecordService;

    /**
     * 获取文章评论列表
     *
     * @param session
     * @param articleId
     * @param pageNo
     * @param orderType
     * @return
     */
    @RequestMapping("/loadComment")
    @Globallnterceptor(checkParams = true)
    public ResponseVO loadComment(HttpSession session,
                                  @VerifyParam(required = true) String articleId,
                                  Integer pageNo,
                                  Integer orderType) {
        //默认按照点赞数排序（最热排序）
        final String ORDER_TYPE0 = "good_count desc,comment_id asc";
        //默认按照时间排序(最新排序）
        final String ORDER_TYPE1 = "comment_id desc";

        //读取配置类是否没有开启评论
        if (!SysCacheUtils.getSysSetting().getCommentSetting().getCommentOpen()) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }

        ForumCommentQuery commentQuery = new ForumCommentQuery();
        commentQuery.setArticleId(articleId);
        String orderBy = orderType == null || orderType == Constants.ZERO ? ORDER_TYPE0 : ORDER_TYPE1;
        //置顶肯定是最前面的
        commentQuery.setOrderBy("top_type desc," + orderBy);
        //获取存在session中的登录信息
        SessionWebUserDto userDto = getUserInfoFromSession(session);
        //判断有登录信息
        if (userDto != null) {
            commentQuery.setQueryLikeType(true);
            commentQuery.setCurrentUserId(userDto.getUserId()); //当前登录用户id
        } else {
            commentQuery.setStatus(ArticleStatusEnum.AUDIT.getStatus());
        }
        commentQuery.setPageNo(pageNo);
        commentQuery.setPageSize(PageSize.SIZE50.getSize());
        commentQuery.setpCommentId(0);
        commentQuery.setLoadChildren(true);

        //返回数据
        return getSuccessResponseVO(forumCommentService.findListByPage(commentQuery));
    }

    /**
     * 评论列表点赞
     *
     * @param session
     * @param commentId
     * @return
     */
    @RequestMapping("/doLike")
    @Globallnterceptor(checkParams = true, checkLogin = true)
    public ResponseVO doLike(HttpSession session,
                             @VerifyParam(required = true) Integer commentId) {
        //获取登录的用户信息
        SessionWebUserDto sessionWebUserDto = getUserInfoFromSession(session);

        String objectId = String.valueOf(commentId);

        likeRecordService.doLike(objectId, sessionWebUserDto.getUserId(), sessionWebUserDto.getNickName(), OperRecordOpTypeEnum.COMMENT_LIKE);

        //评论点赞完之后还需要将点赞的评论信息返回出去
        LikeRecord likeRecord = likeRecordService.getUserOperRecordByObjectIdAndUserIdAndOpType(objectId, sessionWebUserDto.getUserId(), OperRecordOpTypeEnum.COMMENT_LIKE.getType());
        ForumComment comment = forumCommentService.getForumCommentByCommentId(commentId);
        comment.setLikeType(likeRecord == null ? 0 : 1); // 点赞类型 0未点赞 1已点赞

        return getSuccessResponseVO(comment);
    }

    /**
     * 评论置顶
     *
     * @param session
     * @param commentId
     * @param topType
     * @return
     */
    @RequestMapping("/changeTopType")
    @Globallnterceptor(checkParams = true, checkLogin = true)
    public ResponseVO changeTopType(HttpSession session,
                                    @VerifyParam(required = true) Integer commentId,
                                    @VerifyParam(required = true) Integer topType) {
        SessionWebUserDto userDto = getUserInfoFromSession(session);
        forumCommentService.changeTopType(userDto.getUserId(), commentId, topType);
        return getSuccessResponseVO(null);
    }

    /**
     * 发布评论
     *
     * @param session
     * @param articleId   文章id
     * @param pCommentId  父模版id
     * @param content     内容
     * @param image       图片
     * @param replyUserId 回复用户id
     * @return
     */
    @RequestMapping("/postComment")
    @Globallnterceptor(checkParams = true, checkLogin = true) //frequencyType = UserOperFrequencyTypeEnum.POST_COMMENT
    public ResponseVO postComment(HttpSession session,
                                  @VerifyParam(required = true) String articleId,
                                  @VerifyParam(required = true) Integer pCommentId,
                                  @VerifyParam(min = 5, max = 800) String content,
                                  MultipartFile image,
                                  String replyUserId) {
        //读取配置类是否没有开启评论
        if (!SysCacheUtils.getSysSetting().getCommentSetting().getCommentOpen()) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (image == null && StringTools.isEmpty(content)) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        SessionWebUserDto sessionWebUserDto = getUserInfoFromSession(session);

        //将内容进行一个转义 防止用户写html和js
        content = StringTools.escapeHTML(content);
        ForumComment forumComment = new ForumComment();
        forumComment.setUserId(sessionWebUserDto.getUserId());
        forumComment.setNickName(sessionWebUserDto.getNickName());
        forumComment.setUserIpAddress(sessionWebUserDto.getProvince());
        forumComment.setpCommentId(pCommentId);
        forumComment.setArticleId(articleId);
        forumComment.setContent(content);
        forumComment.setReplyUserId(replyUserId);
        forumComment.setTopType(CommentTopTypeEnum.NO_TOP.getType());
        forumCommentService.postComment(forumComment, image);

        //pCommentId不为0 表示是二级评论 查询下面的所有二级评论
        if (pCommentId != 0) {
            ForumCommentQuery forumCommentQuery = new ForumCommentQuery();
            forumCommentQuery.setArticleId(articleId);
            forumCommentQuery.setpCommentId(pCommentId);
            forumCommentQuery.setOrderBy("comment_id asc");
            List<ForumComment> children = forumCommentService.findListByParam(forumCommentQuery); //查询二级评论
            return getSuccessResponseVO(children); //返回二级评论
        }
        //返回一级评论
        return getSuccessResponseVO(forumComment);
    }
}
